package com.john.demo.bio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SocketUtils {

    /**
     * 从socket中读取一行消息
     * @param socket
     * @return
     */
    public static String readLine(Socket socket) {
        String line = null;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            line = br.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return line;
    }

    /**
     * 将一行文本通过Socket发送出去
     * @param socket
     * @param line
     */
    public static void writeLine(Socket socket, String line) {
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
            if(!line.endsWith("\n")) {
                line += "\n";
            }
            writer.write(line);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
